#include "string.h"

string *str_new()
{
	return (string *) ll_new();
}

string *str_cpy(string *s)
{
	string *aux = str_new();
	str_cat(aux, s);
	return aux;
}

string *str_read_line()
{
    string *line = str_new();
    char c;
    while( (c = getchar()) != '\n') str_catc(line, c);
    return line;
}

void str_delete(void *s)
{
	ll_delete(s, free);
}

int str_lenght(string *s)
{
	return ll_length(s);
}

void str_replace(string *s, string *c)
{
    ll_iterator *it = ll_get_iterator(s);
    while(!ll_is_end(it)) ll_remove(it, free);
    free(it);
    str_cat(s, c);
}

void str_catc(string *s, char c)
{
	char *ca = (char *) malloc(sizeof(char));
	*ca = c;
	ll_insert_last(s, ca);
}

void str_cats(string *s, char c[])
{
	while(*c != '\0')
	{
		str_catc(s, *c);
		c++;
	}
}

void str_cat(string *s, string *c)
{
	ll_iterator *it = ll_get_iterator(c);
	while(!ll_is_end(it))
	{
		str_catc(s, str_get_char(it));
		ll_next(it);
	}
	free(it);
}

int str_starts_with(string *s, char c[])
{
	int i = 0;
	int ret = 1;
	ll_iterator *it = ll_get_iterator(s);

	while(!ll_is_end(it) && c[i] != '\0' && ret)
	{
		ret = (str_get_char(it) == c[i]);
		ll_next(it);
		i++;
	}

	if(ret) ret = (c[i] == '\0');
	free(it);
	return ret;
}

int str_equals(string *s, char *c)
{
	int ret = 1;
	ll_iterator *it = ll_get_iterator(s);

	while(!ll_is_end(it) && *c != '\0' && ret)
	{
		ret = (str_get_char(it) == *c);
		ll_next(it);
		c++;
	}

	if(ret) ret = (ll_is_end(it) && *c == '\0');
	free(it);
	return ret;
}

int str_equal(string *s, string *c)
{
    int ret = 1;
    ll_iterator *it1 = ll_get_iterator(s);
    ll_iterator *it2 = ll_get_iterator(c);

    while(!ll_is_end(it1) && !ll_is_end(it2) && ret)
    {
        ret = (str_get_char(it1) == str_get_char(it2));
        ll_next(it1);
        ll_next(it2);
    }

    if(ret) ret = (ll_is_end(it1) && ll_is_end(it2));
    free(it1);
    free(it2);
    return ret;
}

char *str_to_array(string *s)
{
	int i = 0;
	char *c = (char *) malloc( (ll_length(s) + 1) * sizeof(char));
	ll_iterator *it = ll_get_iterator(s);

	while(!ll_is_end(it))
	{
		c[i] = str_get_char(it);
		ll_next(it);
		i++;
	}
	c[i] = '\0';

	free(it);
	return c;
}

char str_get_char(ll_iterator *i)
{
	return * (char *) ll_get(i);
}

void str_print(string *s, FILE *f)
{
    ll_iterator *it = ll_get_iterator(s);
    while(!ll_is_end(it))
    {
        fputc(str_get_char(it), f);
        ll_next(it);
    }
    free(it);
}
